/**
 * 测试调度器无缝衔接逻辑
 * 验证过期检测、关闭、结算、创建新期数的流程
 */

const { Client } = require('pg');

// 数据库配置
const dbConfig = {
  host: 'localhost',
  port: 5432,
  database: 'your_database_name',
  user: 'your_username',
  password: 'your_password'
};

async function testSchedulerSeamless () {
  const client = new Client(dbConfig);

  try {
    await client.connect();
    console.log('✅ 数据库连接成功');

    // 测试过期检测逻辑
    console.log('\n🔍 测试过期检测逻辑...');

    const now = new Date();
    const oneMinuteAgo = new Date(now.getTime() - 60 * 1000);
    const oneMinuteLater = new Date(now.getTime() + 60 * 1000);

    // 查询过期的期数
    const expiredDiceQuery = `
      SELECT 
        id, status, start_time, end_time, 
        CASE 
          WHEN end_time < NOW() THEN '已过期'
          WHEN end_time > NOW() THEN '未过期'
          ELSE '刚好到期'
        END as expiry_status
      FROM casino_dice_rounds 
      WHERE status = 0 
      ORDER BY end_time DESC 
      LIMIT 10
    `;

    const expiredDice = await client.query(expiredDiceQuery);
    console.log(`找到 ${expiredDice.rows.length} 个下注中的大小期数`);

    expiredDice.rows.forEach(round => {
      console.log(`期数 ${round.id}: ${round.expiry_status} (结束时间: ${round.end_time})`);
    });

    // 查询过期的赤壁期数
    const expiredChibiQuery = `
      SELECT 
        id, status, start_time, end_time,
        CASE 
          WHEN end_time < NOW() THEN '已过期'
          WHEN end_time > NOW() THEN '未过期'
          ELSE '刚好到期'
        END as expiry_status
      FROM casino_chibi_rounds 
      WHERE status = 0 
      ORDER BY end_time DESC 
      LIMIT 10
    `;

    const expiredChibi = await client.query(expiredChibiQuery);
    console.log(`找到 ${expiredChibi.rows.length} 个下注中的赤壁期数`);

    expiredChibi.rows.forEach(round => {
      console.log(`期数 ${round.id}: ${round.expiry_status} (结束时间: ${round.end_time})`);
    });

    // 测试调度流程模拟
    console.log('\n🔄 模拟调度流程...');

    // 1. 检测过期期数
    const actuallyExpiredDice = expiredDice.rows.filter(r => r.expiry_status === '已过期');
    const actuallyExpiredChibi = expiredChibi.rows.filter(r => r.expiry_status === '已过期');

    console.log(`步骤1 - 检测过期期数:`);
    console.log(`  大小玩法: ${actuallyExpiredDice.length} 个过期期数`);
    console.log(`  赤壁玩法: ${actuallyExpiredChibi.length} 个过期期数`);

    // 2. 模拟关闭过期期数
    console.log(`\n步骤2 - 关闭过期期数:`);
    for (const round of actuallyExpiredDice) {
      console.log(`  关闭大小期数 ${round.id}: BETTING(0) -> DRAWING(1)`);
    }
    for (const round of actuallyExpiredChibi) {
      console.log(`  关闭赤壁期数 ${round.id}: BETTING(0) -> DRAWING(1)`);
    }

    // 3. 模拟结算已关闭期数
    console.log(`\n步骤3 - 结算已关闭期数:`);

    // 查询需要结算的期数（状态为DRAWING且有开奖结果）
    const settleDiceQuery = `
      SELECT id, status, num1, num2, num3
      FROM casino_dice_rounds 
      WHERE status = 1 
        AND num1 IS NOT NULL 
        AND num2 IS NOT NULL 
        AND num3 IS NOT NULL
      ORDER BY id DESC 
      LIMIT 5
    `;

    const settleDice = await client.query(settleDiceQuery);
    console.log(`  找到 ${settleDice.rows.length} 个需要结算的大小期数`);

    const settleChibiQuery = `
      SELECT id, status, winning_side
      FROM casino_chibi_rounds 
      WHERE status = 1 
        AND winning_side IS NOT NULL
        AND winning_side >= 1 
        AND winning_side <= 3
      ORDER BY id DESC 
      LIMIT 5
    `;

    const settleChibi = await client.query(settleChibiQuery);
    console.log(`  找到 ${settleChibi.rows.length} 个需要结算的赤壁期数`);

    // 4. 模拟创建新期数
    console.log(`\n步骤4 - 创建新期数:`);

    // 检查当前是否有活跃期数
    const currentDiceQuery = `
      SELECT COUNT(*) as count 
      FROM casino_dice_rounds 
      WHERE status = 0
    `;

    const currentChibiQuery = `
      SELECT COUNT(*) as count 
      FROM casino_chibi_rounds 
      WHERE status = 0
    `;

    const [currentDice] = await client.query(currentDiceQuery);
    const [currentChibi] = await client.query(currentChibiQuery);

    console.log(`  当前活跃期数: 大小玩法 ${currentDice.count} 个, 赤壁玩法 ${currentChibi.count} 个`);

    if (currentDice.count === 0) {
      console.log(`  ✅ 需要创建新的大小期数`);
    } else {
      console.log(`  ℹ️ 大小玩法已有活跃期数，跳过创建`);
    }

    if (currentChibi.count === 0) {
      console.log(`  ✅ 需要创建新的赤壁期数`);
    } else {
      console.log(`  ℹ️ 赤壁玩法已有活跃期数，跳过创建`);
    }

    // 检查时间连续性
    console.log('\n⏰ 检查时间连续性...');

    const timeContinuityQuery = `
      SELECT 
        id, start_time, end_time,
        LAG(end_time) OVER (ORDER BY id) as prev_end_time,
        start_time - LAG(end_time) OVER (ORDER BY id) as time_gap
      FROM casino_dice_rounds 
      ORDER BY id DESC 
      LIMIT 5
    `;

    const timeContinuity = await client.query(timeContinuityQuery);
    console.log('最近5期的时间连续性:');

    timeContinuity.rows.forEach((round, index) => {
      if (index === 0) {
        console.log(`  期数 ${round.id}: 开始 ${round.start_time} (第一期)`);
      } else {
        const gapMs = round.time_gap ? Math.round(round.time_gap / 1000) : 0;
        const gapStatus = gapMs === 0 ? '✅ 无缝' : gapMs > 0 ? '⚠️ 有间隙' : '❌ 重叠';
        console.log(`  期数 ${round.id}: 开始 ${round.start_time}, 与上期间隔 ${gapMs}秒 ${gapStatus}`);
      }
    });

    // 检查潜在问题
    console.log('\n🚨 检查潜在问题...');

    // 1. 检查是否有卡在下注状态的过期期数
    const stuckRoundsQuery = `
      SELECT COUNT(*) as count 
      FROM casino_dice_rounds 
      WHERE status = 0 AND end_time < NOW() - INTERVAL '1 minute'
    `;

    const [stuckRounds] = await client.query(stuckRoundsQuery);
    if (stuckRounds.count > 0) {
      console.log(`  ❌ 发现 ${stuckRounds.count} 个卡在下注状态的过期期数`);
    } else {
      console.log(`  ✅ 没有卡在下注状态的过期期数`);
    }

    // 2. 检查是否有卡在开奖状态的期数
    const stuckDrawingQuery = `
      SELECT COUNT(*) as count 
      FROM casino_dice_rounds 
      WHERE status = 1 AND end_time < NOW() - INTERVAL '5 minutes'
    `;

    const [stuckDrawing] = await client.query(stuckDrawingQuery);
    if (stuckDrawing.count > 0) {
      console.log(`  ❌ 发现 ${stuckDrawing.count} 个卡在开奖状态的期数`);
    } else {
      console.log(`  ✅ 没有卡在开奖状态的期数`);
    }

    console.log('\n🎉 调度器无缝衔接测试完成！');

  } catch (error) {
    console.error('❌ 测试失败:', error.message);
  } finally {
    await client.end();
  }
}

// 运行测试
if (require.main === module) {
  testSchedulerSeamless().catch(console.error);
}

module.exports = { testSchedulerSeamless };
